import { createVNode, render } from 'vue'
import ContextmenuComponent from '@/components/Contextmenu/index'

const CTX_CONTEXTMENU_HANDLER = 'CTX_CONTEXTMENU_HANDLER'

const mycontextmenu = {
  name: 'mycontextmenu',

  mounted (el, binding) {
    el[CTX_CONTEXTMENU_HANDLER] = (event) => contextmenuListener(el, event, binding)
    el.addEventListener('contextmenu', el[CTX_CONTEXTMENU_HANDLER])
  },
  updated (el, binding, vnode, prevVnode) {

  },
  unmounted (el) {
    if (el && el[CTX_CONTEXTMENU_HANDLER]) {
      el.removeEventListener('contextmenu', el[CTX_CONTEXTMENU_HANDLER])
      delete el[CTX_CONTEXTMENU_HANDLER]
    }
  }
}

const contextmenuListener = function (el, event, binding) {
  event.stopPropagation()
  event.preventDefault()

  const menus = binding.value
  if (!menus) return

  let container = null

  // 移除右键菜单并取消相关的事件监听
  const removeContextmenu = () => {
    if (container) {
      document.body.removeChild(container)
      container = null
    }
    document.body.removeEventListener('scroll', removeContextmenu)
    window.removeEventListener('resize', removeContextmenu)
  }

  container = document.createElement('div')
  container.className = 'contextmenu-pop'
  container.onmousedown = function () {
    removeContextmenu()
  }
  container.oncontextmenu = function (e) {
    e.preventDefault()
    removeContextmenu()
  }
  const vm = createVNode(ContextmenuComponent, {
    axis: { x: event.x, y: event.y },
    el,
    menus,
    removeContextmenu
  })
  render(vm, container)

  document.body.appendChild(container)
  // 页面变化时移除菜单
  document.body.addEventListener('scroll', removeContextmenu)
  window.addEventListener('resize', removeContextmenu)
}

export { mycontextmenu }
